﻿#include "widget.h"
#include "./ui_widget.h"

#include <QDebug>
#include <QMessageBox>

#include <libdaq/device/DAQ331M/daq_331_m.h>

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_DCPushButton_clicked()
{
    auto dac_channel = DAQDACChannel::DAC1;
    daq331m.StopDAC(dac_channel);
    auto dac_mode = DAQDACMode::DirectCurrent;
    daq331m.ConfigDACMode(dac_channel, dac_mode);
    /* 输出直流 v：10v 范围为0.000V - 15.000V */
    auto dac_dc_data = 10.0;
    daq331m.ConfigDACDirectCurrentData(dac_channel, dac_dc_data);
    if (daq331m.StartDAC(dac_channel))
    {
        QMessageBox::information(this, u8"提示", u8"通道1输出直流电压10V");
    }
}

void Widget::on_ACPushButton_clicked()
{
    auto dac_channel = DAQDACChannel::DAC1;
    daq331m.StopDAC(dac_channel);
    auto dac_mode = DAQDACMode::Wave;
    daq331m.ConfigDACMode(dac_channel, dac_mode);
    /* 输出波形为 vpp：5v frequent:100hz 的正弦波 */
    auto frequent = 100;
    auto vpp = 5.0;
    auto wave_data = std::vector<double>(1000);
    auto temp_f = 2 * 3.14159 / 1000;
    for (int i = 1; i <= 1000; i++)
    {
        wave_data[i - 1] = 0.5 * vpp * (sin(temp_f * i) + 1) * 0.273; // 这里的0.273是为了将数据转换为0-15V的范围
    }
    daq331m.ConfigDACWaveData(dac_channel, frequent, wave_data);
    if (daq331m.StartDAC(dac_channel))
    {
        QMessageBox::information(this, u8"提示", u8"通道1输出正弦波");
    }
}

void Widget::on_ConnectPushButton_clicked()
{
#if defined(USE_RS485) && !defined(USE_TCP_CLIENT) && !defined(USE_MODBUS)
    daq331m.UseSerialBackend(R"(\\.\COM20)", 115200);
#elif defined(USE_TCP_CLIENT) && !defined(USE_RS485) && !defined(USE_MODBUS)
    daq331m.UseTCPClientBackend("192.168.1.100", 8000);
#elif defined(USE_MODBUS) && !defined(USE_RS485) && !defined(USE_TCP_CLIENT)
    daq331m.UseModbusRTUBackend(R"(\\.\COM20)", 115200, 1);
#endif

    // 初始化一个DAQ设备
    if (!daq331m.InitializeDevice())
    {
        qDebug() << (u8"libdaq初始化设备失败");
    }
    else
    {
        qDebug() << (u8"libdaq初始化设备成功");
    }

    // 连接一个DAQ设备
    if (!daq331m.ConnectedDevice())
    {
        qDebug() << (u8"libdaq连接设备失败");
    }
    else
    {
        qDebug() << (u8"libdaq连接设备成功");
    }
}
